from decimal import InvalidOperation, Decimal

from rest_framework import serializers
from .models import ShipSegment


class ShipSegmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShipSegment
        fields = '__all__'

    def create(self, validated_data):
        return ShipSegment.objects.create(**validated_data)


class FlexibleDecimalField(serializers.DecimalField):
    def __init__(self, **kwargs):
        kwargs.setdefault('max_digits', 15)
        kwargs.setdefault('decimal_places', 2)
        kwargs.setdefault('required', False)
        super().__init__(**kwargs)

    def to_internal_value(self, data):
        if data is None:
            return data

        if isinstance(data, (int, float)):
            data = str(data)

        if isinstance(data, str):
            data = data.strip().replace(',', '').replace('，', '')

        try:
            return Decimal(data)
        except (InvalidOperation, ValueError):
            raise serializers.ValidationError(f'"{data}" 不是一个有效的数字。')


class ShipSegmentImportSerializer(serializers.Serializer):
    ship_number = serializers.CharField(max_length=50)
    ship_type = serializers.CharField(max_length=100)
    segment_number = serializers.CharField(max_length=50)
    station_cycle = serializers.CharField(allow_blank=True, required=False)
    segment_length = FlexibleDecimalField()
    segment_width = FlexibleDecimalField()
    segment_height = FlexibleDecimalField()
    segment_weight = FlexibleDecimalField()

    def validate_ship_number(self, value):
        if not value.strip():
            raise serializers.ValidationError("船号不能为空")
        return value

    def validate_ship_type(self, value):
        if not value.strip():
            raise serializers.ValidationError("船型不能为空")
        return value

    def validate_segment_number(self, value):
        if not value.strip():
            raise serializers.ValidationError("分段号不能为空")
        return value

    def create(self, validated_data):
        return ShipSegment(**validated_data)

    def update(self, instance, validated_data):
        for key, value in validated_data.items():
            setattr(instance, key, value)
        return instance
